import random
import requests
import re
import os
import sys

url = 'http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word='

# url = url + sys.argv[1]
info = input("请输入关键字:")
url = url + info

def start(url):
    r = requests.get(url)
    html = r.text
    imgUrl_list = re.findall('"objURL":"(.*?)"', html, re.S)
    for imgUrl in imgUrl_list:
        path = 'baidu_img/' + info + str(random.randrange(1, 1000)) + '.jpg'
        print("正在抓取 " + info + ": " + imgUrl[:30])
        if not os.path.exists(path):
            r = requests.get(imgUrl)
            with open(path, 'wb') as f:
                f.write(r.content)


start(url)
